import logging
import unittest

from api.order_api import OrderApi
from common.db_util import DBUtil
import config.db_cnf as db_cnf
import config.params_cnf as params_cnf


class TestUserOrder(unittest.TestCase):
    dbUtil = None
    order_id = None
    order_no = None

    @classmethod
    def setUp(cls) -> None:
        cls.dbUtil = DBUtil(host=db_cnf.host, port=db_cnf.port,
                            user=db_cnf.user, password=db_cnf.password,
                            database=db_cnf.database)

    def test01_order_by_user(self):
        print('获取用户订单列表')

        resp = OrderApi().order_by_user(params_cnf.PAGE)
        self.assertEqual(200, resp.status_code)

        # 预期结果：page页的个数【每一页15条数据，limit (n-1)*x+i,m】
        limit_0 = (int(params_cnf.PAGE) - 1) * 15
        sql = f"SELECT count(*) FROM (select * FROM `order` WHERE user_id = '8' LIMIT {limit_0},15) AS temp"
        db_data = self.dbUtil.dql_one(sql)[0]
        logging.info(db_data)

        resp_list_num = len(resp.json().get('data'))
        self.assertEqual(db_data, resp_list_num)

    def test02_add_order(self):
        print('创建订单')

        resp = OrderApi().add_order(params_cnf.ORDER_DATA)
        self.assertEqual(200, resp.status_code)
        self.assertTrue(resp.json().get('pass'))

        TestUserOrder.order_id = resp.json().get('order_id')
        TestUserOrder.order_no = resp.json().get('order_no')

    def test03_query_order(self):
        print('查看订单')

        # 断言创建订单时生成的订单信息
        resp = OrderApi().query_order(TestUserOrder.order_id)
        self.assertEqual(200, resp.status_code)
        self.assertEqual(TestUserOrder.order_no, resp.json().get('order_no'))
